# encoding: utf-8
import sys
import os
import time
import traceback
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
sys.path.append("..")
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit
from flask_cors import *

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
CORS(app, supports_credentials=True)
socketio = SocketIO()
socketio.init_app(app,cors_allowed_origins="*")
client_name_space = '/client'
admin_name_space = '/admin'
admin_list = {}
host_list = {}
@app.route('/')
def index():
    """加载HTML客户端"""
    return render_template('index.html')

@app.route('/push')
def push_once():
    """广播消息
    发送消息：http://127.0.0.1:5000/push?msg=a
    """
    event_name = 'broadcast message'
    data = request.args.get("msg")
    broadcasted_data = {'data': data}
    print("publish msg==>", broadcasted_data)
    socketio.emit(event_name, broadcasted_data, broadcast=True)
    return 'send msg successful!'

@socketio.on('join admin')
def join_admin(data):
    try:
        print('admin join:',data['username'])
        if data['username'] == 'admin' and data['token'] == 'admin888':
            admin_list[data['username']] = {
                'token':data['token'],
                'ctime':time.time(),
                'atime':time.time(),
                'sid':request.sid
            }
        print(admin_list)
    except:
        traceback.print_exc()
    # emit('message', {'data': message['data']})

@socketio.on('execute result')
def execute_result(data):
    print(data)
    emit('exec result',{'result':data['result'],'client_sid':data['client_sid']},room=data['admin_sid'])

@socketio.on('join host')
def join_host(data):
    print(data)
    print('join host:',data['key'])
    try:
        host_list[data['key']] = {
            'ctime': time.time(),
            'atime': time.time(),
            'sid': request.sid
        }
        notice_all_admin('host '+ data['key'] + ' joined.')
    except:
        traceback.print_exc()
    # emit('message', {'data': message['data']})

def notice_all_admin(message):
    for admin_name in list(admin_list.keys()):
        socketio.emit('notice',{'data':message},room=admin_list[admin_name]['sid'])

@socketio.on('exec command')
def exec_command(data):
    key = data['key']
    admin_sid = request.sid
    client_sid = get_client_sid(key)
    if client_sid == 0:
        socketio.emit('notice', {'data': 'host:'+key+'is not online.'}, room=admin_sid)
    else:
        socketio.emit('exec command',{'admin_sid':admin_sid,'command':data['command']},room=client_sid)

def get_client_sid(key):
    for host_name in list(host_list.keys()):
        if host_name == key:
            return host_list[host_name]['sid']
    return 0

def del_target(sid):
    for admin_name in list(admin_list.keys()):
        if admin_list[admin_name]['sid'] == sid:
            del admin_list[admin_name]

    for host_key in list(host_list.keys()):
        if host_list[host_key]['sid'] == sid:
            del host_list[host_key]

@socketio.on('recevice message')
def test_message(message):
    print('recevice message', message)
    # emit('message', {'data': message['data']})

@socketio.on('connect')
def connected_msg():
    """客户端连接"""
    print('client connected!', request.sid)


@socketio.on('disconnect')
def disconnect_msg():
    """客户端离开"""
    print('client disconnected:',request.sid)


if __name__ == '__main__':

    print("conent http://127.0.0.1:5000")
    socketio.run(app, host='0.0.0.0', port=5000)
